package com.kuangjia.boss.commonSafety.aes;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.context.annotation.DependsOn;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;

/**
 * @Description 用于数据库加密类
 * @Date 13:43 2020/12/8
 **/
@DependsOn("iVPropertiesParse")
public class AESUtils {

    private static String IV = "";

    static {
      //   IV = IVPropertiesParse.getValue("iv");
       IV = "hE2zG3kG5yM8wT4nF0mA9sY2hL";
    }

    private static final String ALGORITHMSTR = "AES/GCM/NoPadding";

    private static final String DEFAULT_CODING = "utf-8";

    /**
     * 如果报错java.security.NoSuchProviderException: no such provider: BC，那么需要加上这一段，同时需要bcprov-jdk15on.jar
     */
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * @Description 加密
     * @Date 14:25 2020/12/7
     **/
    public static String aesEncrypt(String content, String key) throws Exception {
        byte[] input = content.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
        IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(DEFAULT_CODING));
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, skc, ivspec);
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
        return Base64.getEncoder().encodeToString(cipherText);
    }


    /**
     * @Description 解密
     * @Date 14:26 2020/12/7
     **/
    public static String aesDecrypt(String tmp, String key) throws Exception {
        byte[] keyb = key.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(keyb);
        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
        IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(DEFAULT_CODING));
        Cipher dcipher = Cipher.getInstance(ALGORITHMSTR, "BC");
        dcipher.init(Cipher.DECRYPT_MODE, skey, ivspec);
        byte[] clearbyte = dcipher.doFinal(Base64.getDecoder().decode(tmp));
        return new String(clearbyte, DEFAULT_CODING);
    }

    public static void main(String[] args) throws Exception {
        String origin = "133121";
        String encryptstr = aesEncrypt(origin,IV);
        System.out.println(encryptstr);

        String decryptstr = aesDecrypt(encryptstr,IV);
        System.out.println(decryptstr);

    }
}